package org.jiajin2coding.reggie.exception;

import lombok.extern.slf4j.Slf4j;
import org.jiajin2coding.reggie.common.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author Guo Jinhua (jiajin2coding)
 * @version 1.0.0
 * @className GlobalExceptionHandler
 * @description 全局异常处理
 * @date 2023-10-27
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResultVO<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String errMsg = split[2] + "用户信息已存在";
            return ResultVO.error(errMsg);
        }
        return ResultVO.error("未知错误，数据库操作异常，操作失败! ");
    }

}
